//
//  DemoViewController.m
//  MySpaceID
//
//  Created by Haider Sabri on Monday6/8/09.
//  Copyright 2009 MySpace, Inc. All rights reserved.
//

#import "DemoViewController.h"
#import "OffsiteContext.h"
#import "PortableContacts.h"
#import "XPathQuery.h" 

@implementation DemoViewController
@synthesize context;
@synthesize api;
@synthesize urlReturn;
@synthesize userId;
@synthesize masterFriendList;
@synthesize masterImageUrl;
@synthesize masterUserIds;
@synthesize masterUsername;
@synthesize friendImageView;
@synthesize profileImageView;
@synthesize statusTextView;
@synthesize statusTextField;

#pragma mark -
#pragma mark UIView Methods
- (IBAction) updateAction: (id) sender
{
	if(api)
	{
		[api setMoodStatus:userId moodId:0 moodName:nil moodPictureName:nil status:[statusTextField text]];
		[self parseStatusData: [api getStatus:userId]];
	}
	[statusTextField resignFirstResponder];

}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];
	
	if(context == nil)
	{
		context = [OffsiteContext contextWithConsumerKey:@"18bed0f4247a4f79bc9941bfed5b534c"  
							  consumerSecret:@"2e8ebdafbef844a5929086e659e4188c" tokenKey:nil tokenSecret:nil] ;
		[context setUrlScheme:@"myspaceid2"];
		[context retain];
		
		
	}
	NSString *returnUrl = [[NSUserDefaults standardUserDefaults] objectForKey:@"url"];
	if(returnUrl)
	{
		[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"url"];
		[[NSUserDefaults standardUserDefaults] synchronize];
		[context getAccessToken];		
	}
	
	bool loggedIn = [context isLoggedIn];
	if(loggedIn)
	{
		// Add a left button
		self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]
												  initWithTitle:@"Logout" 
												  style:UIBarButtonItemStylePlain 
												  target:self 
												  action:@selector(logOut)] autorelease];
		
		self.api = [RestV1 apiWithContext: context] ;
		[api retain];
		NSData *userData = [api getCurrentUser];
		[self parseUserData:userData];
		userData = [api getStatus:userId];
		[self parseStatusData:userData];
		userData = [api getFriends:userId];
		[self parseFriendsData:userData];
		/*
		PortableContacts *pApi = [PortableContacts apiWithContext:context];
		userData = [pApi getSelf];
		userData = [pApi getFriends];
		userData = nil;
		 */
	}
	else
	{
		// Add a left button
		self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]
												  initWithTitle:@"Login" 
												  style:UIBarButtonItemStylePlain 
												  target:self 
												  action:@selector(logIn)] autorelease];
	}
	
}
- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	[statusTextField resignFirstResponder];
	return YES;
}


- (void)dealloc {
	[context release];
	[api release];
	[masterFriendList release];
	[masterImageUrl release];
	[masterUserIds release];
	[masterUsername release];
	[friendImageView release];
	[profileImageView release];
	[super dealloc];
}
#pragma mark -
#pragma mark Authentication

-(void) logIn
{
	[context getRequestToken];
	
}

-(void) logOut
{
	[context logOut];
	
	for(UIView *view in self.view.subviews)
	{
		[view removeFromSuperview];
		
	}
	// Add a left buttonˆ
	self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]
											  initWithTitle:@"Login" 
											  style:UIBarButtonItemStylePlain 
											  target:self 
											  action:@selector(logIn)] autorelease];
}


#pragma mark -
#pragma mark ParseData Methods

- (void) parseFriendsData: (NSData*) data
{
	
	if(data)
	{
		
		masterFriendList = PerformXMLXPathQuery2(data, @"//ms:user/ms:friends/ms:user", @"ms", @"api-v1.myspace.com");
		NSLog([NSString stringWithFormat: @"%d", [masterFriendList count]]);
		masterUserIds = PerformXMLXPathQuery2(data, @"//ms:user/ms:friends/ms:user/ms:userid", @"ms", @"api-v1.myspace.com");
		NSLog([NSString stringWithFormat: @"%d", [masterFriendList count]]);
		
		NSLog([NSString stringWithFormat: @"%d", [masterFriendList count]]);
		masterUsername = PerformXMLXPathQuery2(data, @"//ms:user/ms:friends/ms:user/ms:displayname", @"ms", @"api-v1.myspace.com");
		NSLog([NSString stringWithFormat: @"%d", [masterFriendList count]]);
		[masterUserIds retain];
		[masterUsername retain];
		
		
		NSArray *result = PerformXMLXPathQuery2(data, @"//ms:user/ms:friends/ms:user/ms:imageuri", @"ms", @"api-v1.myspace.com");
		NSMutableArray *array = [[NSMutableArray alloc] init];
		for(int i = 0; i < [result count]; i++)
		{
			NSDictionary *node = [result objectAtIndex:i];
			NSURL *url = [NSURL URLWithString: [node objectForKey:@"nodeContent"]];
			UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL: url]];
			[array addObject:img];
			
		}
		
		self.masterImageUrl = [[NSArray alloc] initWithArray:array];
		friendImageView.animationImages = masterImageUrl;
		friendImageView.animationDuration = 5.0;
		[self.friendImageView startAnimating];
		[array release];
	}
	
	
	
}

- (void) parseStatusData: (NSData*) data
{
	if(data)
	{
		NSArray *result = PerformXMLXPathQuery2(data	, @"//ms:user/ms:status", @"ms", @"api-v1.myspace.com");
		NSDictionary *node = [result objectAtIndex:0];
		NSString *value = [node objectForKey:@"nodeContent"];
		if(value)
		{
			statusTextView.text = value;
		}
		
	}
}

- (void) parseUserData: (NSData*) data
{
	if(data)
	{
		NSArray *result = PerformXMLXPathQuery2(data, @"//ms:user/ms:imageuri", @"ms", @"api-v1.myspace.com");
		NSDictionary *node = [result objectAtIndex:0];
		NSString *value = [node objectForKey:@"nodeContent"];
		if(value)
		{
			NSURL *url = [NSURL URLWithString: value];
			UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
			[self.profileImageView setImage:img];
			[profileImageView setUserInteractionEnabled:NO];
		}
		result = PerformXMLXPathQuery2(data, @"//ms:user/ms:userid", @"ms", @"api-v1.myspace.com");
		node = [result objectAtIndex:0];
		value = [node objectForKey:@"nodeContent"];
		if(value)
		{
			userId = [value integerValue];
		}
		
		result = PerformXMLXPathQuery2(data, @"//ms:user/ms:displayname", @"ms", @"api-v1.myspace.com");
		node = [result objectAtIndex:0];
		value = [node objectForKey:@"nodeContent"];
		if(value)
		{
			self.title = value;
		}
	}
}






@end
